package edu.unindra.company.gui;

import java.awt.Component;
import java.awt.Dimension;

import javax.imageio.ImageIO;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;

import edu.unindra.company.dao.entity.Empl;
import edu.unindra.company.dao.impl.EmployeeImpl;
import edu.unindra.company.template.ViewPortGlass;
import usu.widget.ButtonGlass;
import usu.widget.Panel;
import usu.widget.util.WidgetUtilities;

import javax.swing.DefaultComboBoxModel;
import javax.swing.GroupLayout.Alignment;
import javax.swing.GroupLayout;
import javax.swing.LayoutStyle.ComponentPlacement;

import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.awt.Color;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;

import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JTextField;

import net.sf.jasperreports.engine.JRResultSetDataSource;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.xml.JRXmlLoader;

public class FormMainReport extends Panel {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private JTable table;
	private JTextField txtField;
	private ButtonGlass btnPrint;
	private ButtonGlass btnSearch;
	@SuppressWarnings("rawtypes")
	private JComboBox cbField;
	@SuppressWarnings("rawtypes")
	private JComboBox cbOperand;

	private ViewPortGlass viewPort;
	private JScrollPane scrollPane;

	private EmployeeImpl emplIm = null;
	private DefaultTableModel model;

	private String addWhere = "";
	private JasperReport jasperReport;
	private JasperDesign jasperDesign;
	private JasperPrint jasperPrint;

	public FormMainReport() {
		setSize(600, 400);

		emplIm = new EmployeeImpl();

		initComponents();
		initFinals();

	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	private void initComponents() {

		model = new DefaultTableModel();
		model.addColumn("Nim");
		model.addColumn("Nama");
		model.addColumn("Tempat Lahir");
		model.addColumn("Tgl Lahir");
		model.addColumn("Jenis Kelamin");
		model.addColumn("Jabatan");
		model.addColumn("Masa Kerja");
		model.addColumn("No.Telp");
		model.addColumn("Alamat");

		scrollPane = new JScrollPane();

		viewPort = new ViewPortGlass();
		viewPort.setForeground(Color.BLACK);
		viewPort.setBackground(Color.WHITE);
		table = new JTable();
		table.setBackground(Color.WHITE);

		btnPrint = new ButtonGlass();
		btnPrint.setFont(new Font("Tahoma", Font.BOLD, 11));
		btnPrint.setMnemonic('H');
		btnPrint.setText("Print");
		btnPrint.setToolTipText("Klik untuk menghapus operator");
		btnPrint.setRoundRect(true);
		btnPrint.setEnabled(false);
		btnPrint.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				btnPrintActionPerformed(e);
			}
		});

		btnSearch = new ButtonGlass();
		btnSearch.setFont(new Font("Tahoma", Font.BOLD, 11));
		btnSearch.setMnemonic('U');
		btnSearch.setText("Search");
		btnSearch.setToolTipText("Klik untuk mengubah operator");
		btnSearch.setRoundRect(true);
		btnSearch.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				btnSearchActionPerformed(e);
			}
		});

		viewPort.setView(table);
		table.setAutoCreateRowSorter(true);
		table.setForeground(Color.BLACK);
		table.setToolTipText("Tabel Data Karyawan ");
		table.setFillsViewportHeight(true);
		table.setOpaque(false);
		table.setSelectionBackground(new java.awt.Color(51, 255, 52));
		table.setSelectionForeground(new java.awt.Color(0, 0, 0));

		setOpaque(false);
		setOpaqueGradient(false);
		setOpaqueImage(false);

		scrollPane.setBorder(javax.swing.BorderFactory
				.createLineBorder(new java.awt.Color(0, 0, 0)));
		scrollPane.setViewport(viewPort);

		cbField = new JComboBox();
		cbField.setModel(new DefaultComboBoxModel(new String[] { "Nim",
				"Jabatan", "MasaKerja" }));

		JLabel lblField = new JLabel("FIELD :");
		lblField.setFont(new Font("Tahoma", Font.BOLD, 11));

		cbOperand = new JComboBox();
		cbOperand.setModel(new DefaultComboBoxModel(new String[] { "=", ">",
				"<", "like" }));

		txtField = new JTextField();
		txtField.setColumns(10);

		javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
		layout.setHorizontalGroup(layout
				.createParallelGroup(Alignment.TRAILING)
				.addGroup(
						layout.createSequentialGroup()
								.addContainerGap()
								.addGroup(
										layout.createParallelGroup(
												Alignment.TRAILING)
												.addComponent(
														scrollPane,
														GroupLayout.DEFAULT_SIZE,
														766, Short.MAX_VALUE)
												.addGroup(
														layout.createSequentialGroup()
																.addGap(14)
																.addComponent(
																		lblField,
																		GroupLayout.PREFERRED_SIZE,
																		44,
																		GroupLayout.PREFERRED_SIZE)
																.addPreferredGap(
																		ComponentPlacement.RELATED)
																.addComponent(
																		cbField,
																		GroupLayout.PREFERRED_SIZE,
																		141,
																		GroupLayout.PREFERRED_SIZE)
																.addGap(18)
																.addComponent(
																		cbOperand,
																		GroupLayout.PREFERRED_SIZE,
																		58,
																		GroupLayout.PREFERRED_SIZE)
																.addGap(18)
																.addComponent(
																		txtField,
																		GroupLayout.DEFAULT_SIZE,
																		115,
																		Short.MAX_VALUE)
																.addGap(18)
																.addComponent(
																		btnSearch,
																		GroupLayout.PREFERRED_SIZE,
																		GroupLayout.DEFAULT_SIZE,
																		GroupLayout.PREFERRED_SIZE)
																.addGap(18)
																.addComponent(
																		btnPrint,
																		GroupLayout.PREFERRED_SIZE,
																		GroupLayout.DEFAULT_SIZE,
																		GroupLayout.PREFERRED_SIZE)))
								.addContainerGap()));
		layout.setVerticalGroup(layout
				.createParallelGroup(Alignment.TRAILING)
				.addGroup(
						layout.createSequentialGroup()
								.addContainerGap(74, Short.MAX_VALUE)
								.addComponent(scrollPane,
										GroupLayout.PREFERRED_SIZE, 281,
										GroupLayout.PREFERRED_SIZE)
								.addPreferredGap(ComponentPlacement.UNRELATED)
								.addGroup(
										layout.createParallelGroup(
												Alignment.BASELINE)
												.addComponent(
														btnPrint,
														GroupLayout.PREFERRED_SIZE,
														GroupLayout.DEFAULT_SIZE,
														GroupLayout.PREFERRED_SIZE)
												.addComponent(
														cbField,
														GroupLayout.PREFERRED_SIZE,
														GroupLayout.DEFAULT_SIZE,
														GroupLayout.PREFERRED_SIZE)
												.addComponent(lblField)
												.addComponent(
														cbOperand,
														GroupLayout.PREFERRED_SIZE,
														GroupLayout.DEFAULT_SIZE,
														GroupLayout.PREFERRED_SIZE)
												.addComponent(
														btnSearch,
														GroupLayout.PREFERRED_SIZE,
														GroupLayout.DEFAULT_SIZE,
														GroupLayout.PREFERRED_SIZE)
												.addComponent(
														txtField,
														GroupLayout.PREFERRED_SIZE,
														GroupLayout.DEFAULT_SIZE,
														GroupLayout.PREFERRED_SIZE))
								.addContainerGap()));
		this.setLayout(layout);
	}

	@SuppressWarnings({ "rawtypes", "unchecked", "unused" })
	protected void btnPrintActionPerformed(ActionEvent e) {
		if (txtField.getText().length() > 0) {
			ResultSet resultSet;
			try {
				InputStream inputStream = this.getClass().getResourceAsStream(
						"/edu/unindra/company/image/logo_cv1.png");

				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				byte[] buffer = new byte[1024];

				int n = 0;
				while (-1 != (n = inputStream.read(buffer))) {
					baos.write(buffer, 0, n);
				}

				baos.flush();
				byte[] imageInByte = baos.toByteArray();
				baos.close();

				// convert byte array back to BufferedImage
				InputStream in = new ByteArrayInputStream(imageInByte);
				BufferedImage bImageFromConvert = ImageIO.read(in);

				resultSet = emplIm.cetakReport(addWhere);
				JRResultSetDataSource resultSetDataSource = new JRResultSetDataSource(
						resultSet);

				Map inputParameters = new HashMap();
				inputParameters.put("logo", bImageFromConvert);

				InputStream file = getClass().getResourceAsStream(
						"/edu/unindra/company/report/Report.jrxml");
				jasperDesign = JRXmlLoader.load(file);
				jasperReport = JasperCompileManager.compileReport(jasperDesign);

				jasperPrint = JasperFillManager.fillReport(jasperReport,
						inputParameters, resultSetDataSource);
				ReportReview rp = new ReportReview(jasperPrint);
				Dimension screenSize = this.getSize();
				Dimension frameSize = rp.getSize();
				rp.setVisible(true);
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
	}

	protected void btnSearchActionPerformed(ActionEvent e) {
		if (txtField.getText().length() > 0) {

			String field = (String) cbField.getSelectedItem();
			String operand = (String) cbOperand.getSelectedItem();

			if (operand.equals("like")) {
				addWhere = field + " " + operand + "'%" + txtField.getText()
						+ "%'";
			} else {
				addWhere = field + operand + txtField.getText();
			}

			try {
				List<Empl> em = emplIm.getReport(addWhere);

				Object data[][] = new Object[em.size()][9];
				for (int i = 0; i < em.size(); i++) {
					data[i][0] = em.get(i).getNim();
					data[i][1] = em.get(i).getNama();
					data[i][2] = em.get(i).getTeTgl();
					data[i][3] = em.get(i).getTaTgl();
					data[i][4] = em.get(i).getjKelamin();
					data[i][5] = em.get(i).getJabatan();
					data[i][6] = em.get(i).getmKerja();
					data[i][7] = em.get(i).getKontak();
					data[i][8] = em.get(i).getAlamat();

					String[] judul = { "Nim", "Nama", "Tempat Lahir",
							"Tgl Lahir", "Jenis Kelamin", "Jabatan",
							"Masa Kerja", "No.Telp", "Alamat" };
					table.setModel(new DefaultTableModel(data, judul));

				}
			} catch (SQLException e1) {
				e1.printStackTrace();
			}

			btnPrint.setEnabled(true);
		}
	}

	private void initFinals() {
		table.setModel(model);
		table.getTableHeader().setReorderingAllowed(false);
		WidgetUtilities.setAutomaticPopUpMenu(table);
		for (int i = 0; i < table.getColumnCount(); i++) {
			table.getColumnModel().getColumn(i)
					.setCellRenderer(new RenderTable());
		}
	}

	public static class RenderTable extends DefaultTableCellRenderer {

		private static final long serialVersionUID = -1;

		@Override
		public Component getTableCellRendererComponent(JTable table,
				Object value, boolean isSelected, boolean hasFocus, int row,
				int column) {
			if (value != null) {
				setToolTipText(value.toString());
				setOpaque(isSelected);
				return super.getTableCellRendererComponent(table, value,
						isSelected, hasFocus, row, column);
			} else {
				return super.getTableCellRendererComponent(table, value,
						isSelected, hasFocus, row, column);
			}
		}
	}

}
